from flask import current_app, jsonify
from flask import request, g

from info import constants
from info.models import News, Category
from info.response_code import RET
from info.utils.commons import user_login_data
from . import index
from flask import render_template


# 请求路径: /newslist
# 请求方式: GET
# 请求参数: cid,page,per_page
# 返回值: data数据
@index.route('/newslist')
def get_news_list():
    """
    1.获取参数
    2.校验参数
    3.分页查询
    4.返回
    :return:
    """
    # 获取参数
    # 页码
    page = request.args.get('page', 1)
    # 菜单
    cid = request.args.get('cid', 1)
    # 分页显示数量
    per_page = request.args.get('per_page', 10)

    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        per_page = 10
        return jsonify(errno=RET.PARAMERR, errmsg='参数转换异常')
    # 分页查询数据
    filters = [News.status == 0]
    if cid != '1':
        filters.append(News.category_id == cid)

    try:
        pag_news = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询失败')

    # 获取到分页对象中的内容
    currentPage = pag_news.page
    totalPage = pag_news.pages
    items = pag_news.items

    news_list = []
    for item in items:
        news_list.append(item.to_dict())

    data = {
        "currentPage": currentPage,
        "totalPage": totalPage,
        "items": news_list
    }

    return jsonify(errno=RET.OK, errmsg='查询成功', data=data)


@index.route('/favicon.ico')
def get_web_lofo():
    return current_app.send_static_file("news/favicon.ico")


def get_host_news():
    # 获取点击量排行
    try:
        host_news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询失败')

    # 将新闻对象列表转成字典列表
    host_news_list = []
    for host_new in host_news:
        host_news_list.append(host_new.to_dict())
    return host_news_list


def get_category():
    # 查询所有的菜单
    try:
        categroys = Category.query.order_by(Category.id).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询失败')
    # 定义空列表
    categroy_list = []
    for categroy in categroys:
        categroy_list.append(categroy.to_dict())

    return categroy_list


@index.route('/')
@user_login_data
def index():
    # 获取热点新闻列表
    host_news_list = get_host_news()
    # 获取菜单
    categorys = get_category()

    data = {
        'userInfo': g.user.to_dict() if g.user else '',
        'hnewsList': host_news_list,
        'categorys': categorys
    }
    return render_template('news/index.html', data=data)
